<template>
    <div id="body">
        <el-card id="tableCrad">
          <div slot="header" class="clearfix">
            <span>App版本管理</span>
          </div>
          <!-- 查询行开始 -->
          <el-row id="btnRow" type="flex" style="width:100%;"> 
            <el-col :span="20">
              <el-row type="flex">
                <el-tooltip content="唯一号" placement="top" effect="light">
                  <el-input class="input" v-model="app_key" placeholder="请输入唯一号" clearable style="margin-right:10px; width:30%;"></el-input>
                </el-tooltip>
                <el-tooltip content="版本名" placement="top" effect="light">
                  <el-input class="input" v-model="version_name" placeholder="请输入版本名" clearable style="margin-right:10px; width:30%;"></el-input>
                </el-tooltip>
                <el-tooltip content="版本状态" placement="top" effect="light">
                  <el-select v-model="status" @change="getPages" placeholder="请选择用户状态" style="margin-right:10px; width:30%;">
                    <el-option
                      v-for="item in queryStatusOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-tooltip>
                <el-button @click="getPages" icon="el-icon-search" circle></el-button>
              </el-row>
            </el-col>
            <el-col :span="2" :offset="2">
                <el-row>
                  <el-button @click="addOpen" type="primary" icon="el-icon-plus" circle></el-button>
                  <el-button @click="deleteBatch" type="danger" icon="el-icon-delete" circle></el-button>
                </el-row>
            </el-col>
          </el-row>
          <!-- 查询行结束 -->
          <!-- 表格开始 -->
          <el-table
            ref="multipleTable"          
            :data="tableData"
            style="width: 100%"
            :height="tableHeight">
            <el-table-column
                type="selection">
            </el-table-column>
            <el-table-column
              fixed
              prop="id"
              label="编号"
              width="80">
            </el-table-column>
            <el-table-column
              prop="app_key"
              label="唯一号"
              :show-overflow-tooltip="true">
            </el-table-column>
           <el-table-column
              prop="version_name"
              label="版本名"
              align="center"
              width="120">
            </el-table-column>            
            <el-table-column
              prop="version_code"
              label="版本号"
              align="center"
              width="80">
            </el-table-column>
            <el-table-column
              prop="update_status"
              label="强制更新"
              align="center"
              width="80">
              <template slot-scope="scope">
                <div>{{scope.row.update_status === 2 ? '是' : '否'}}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="upload_time"
              label="更新时间">
            </el-table-column>
            <el-table-column
              prop="modify_content"
              label="更新内容"
              :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column
              prop="status"
              label="版本状态"
              align="center"              
              width="80">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.status === 1 ? 'success' : 'danger'"
                  disable-transitions>{{scope.row.status === 1 ? '可用' : '禁用'}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              align="center">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="editOpen(scope.row)"
                  type="text"
                  size="small">
                  编辑
                </el-button>
                <el-button
                  @click.native.prevent="deleteRow(scope.row)"
                  type="text"
                  style="color:red"
                  size="small">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            id="pageDevice"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="paginationData.currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="paginationData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="paginationData.total">
          </el-pagination>
          <!-- 表格结束 -->
        </el-card>
        <!-- 编辑表单开始 -->
        <el-dialog
          title="编辑"
          :visible.sync="editDialogVisible"
          width="80%"
          top="8vh"
          :before-close="editClose"
          v-loading="loading">
          <el-form ref="editForm" :rules="rules" :model="row">
              <el-row type="flex">
                <el-col :span="5">
                  <el-form-item label="编号">
                    <el-input disabled v-model="row.id"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="18" :offset="1">
                  <el-form-item label="应用唯一号 (App Key, 上传apk将会自动生成)" prop="app_key">
                    <el-input v-model="row.app_key"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row type="flex">
                <el-col :span="15">
                    <el-form-item label="版本名 (例如: 1.0.24, 上传apk将会自动生成)" prop="version_name">
                      <el-input v-model="row.version_name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :offset="1">
                    <el-form-item label="版本号 (例如: 24, 上传apk将会自动生成)" prop="version_code">
                      <el-input v-model="row.version_code"></el-input>
                    </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="更新内容">
                <el-input type="textarea" v-model="row.modify_content" :rows="3"></el-input>
              </el-form-item>
              <el-row type="flex"  align="bottom">
                <el-col :span="8">
                  <el-upload
                    class="upload-demo"
                    drag
                    :before-upload="beforeApkUpload"
                    accept=".apk"
                    action>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传apk文件，且不超过100mb</div>
                  </el-upload>
                  <el-tag
                    v-if="file!=null"
                    closable
                    :disable-transitions="false"
                    @close="deleteSubmitFile"
                    type="success">
                    {{file.name}}
                  </el-tag>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否强制更新" label-width="120px" prop="update_status">
                    <el-select v-model="row.update_status" placeholder="请选择">
                      <el-option label="否" :value="1"></el-option>
                      <el-option label="是" :value="2"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="版本状态" label-width="120px" prop="status">
                    <el-select v-model="row.status" placeholder="请选择">
                      <el-option label="可用" :value="1"></el-option>
                      <el-option label="禁用" :value="0"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item> 
                    <el-button type="danger" @click="editClose">取消</el-button>
                    <el-button type="primary" @click="editConfirm">确认编辑</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
        </el-dialog>
        <!-- 编辑表单结束 -->
        <!-- 新添表单开始 -->
        <el-dialog
          title="增加"
          :visible.sync="addDialogVisible"
          width="80%"
          top="8vh"
          :before-close="addClose"
          v-loading="loading">
          <el-form ref="addForm" :rules="rules" :model="row" >
              <el-form-item label="应用唯一号 (App Key, 上传apk将会自动生成)" prop="app_key">
                <el-input v-model="row.app_key"></el-input>
              </el-form-item>
              <el-row type="flex">
                <el-col :span="15">
                    <el-form-item label="版本名 (例如: 1.0.24, 上传apk将会自动生成)" prop="version_name">
                      <el-input v-model="row.version_name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :offset="1">
                    <el-form-item label="版本号 (例如: 24, 上传apk将会自动生成)" prop="version_code">
                      <el-input v-model="row.version_code"></el-input>
                    </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="更新内容">
                <el-input type="textarea" v-model="row.modify_content" :rows="3"></el-input>
              </el-form-item>
              <el-row type="flex"  align="bottom">
                <el-col :span="8">
                  <el-upload
                    class="upload-demo"
                    drag
                    :before-upload="beforeApkUpload"
                    accept=".apk"
                    action>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传apk文件，且不超过100mb</div>
                  </el-upload>
                  <el-tag
                    v-if="file!=null"
                    closable
                    :disable-transitions="false"
                    @close="deleteSubmitFile"
                    type="success">
                    {{file.name}}
                  </el-tag>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否强制更新" label-width="120px" prop="update_status">
                    <el-select v-model="row.update_status" placeholder="请选择">
                      <el-option label="否" :value="1"></el-option>
                      <el-option label="是" :value="2"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="版本状态" label-width="120px" prop="status">
                    <el-select v-model="row.status" placeholder="请选择">
                      <el-option label="可用" :value="1"></el-option>
                      <el-option label="禁用" :value="0"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item>
                    <el-button type="danger" @click="addClose">取消</el-button>
                    <el-button type="primary" @click="addConfirm">立即创建</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
        </el-dialog>
        <!-- 新添表单结束 -->            
    </div>
</template>

<script>
import ApkParser from 'app-info-parser/src/apk'
//const ApkParser = require('app-info-parser/src/apk.js');
export default {
    data() {     
      return {
        //表格高度
        tableHeight: window.innerHeight - 320,
        //分页参数
        tableData: [],
        paginationData: {
            pageSize: 10,
            currentPage: 1,
            total: 50
        },
        //查询参数
        app_key:'',
        version_name:'',
        status: '',
        queryStatusOptions: [{ //绑定model值的是value
          value: '',
          label: '全部'
        }, {
          value: 1,
          label: '可用'
        }, {
          value: 0,
          label: '禁用'
        }],
        //修改或增加用到的的数据
        row:{},
        file:null,
        editDialogVisible: false,
        addDialogVisible: false,
        loading:false,
        rules: {
          app_key: [
            {required: true, message: '请输入唯一码', trigger: 'blur' }
          ],
          version_code: [
            {required: true, message: '请输入版本号', trigger: 'blur'}
          ],
          version_name: [
            {required: true, message: '请输入版本名', trigger: 'blur' },
          ],
          update_status: [
            {required: true, message: '请选择是否强制更新', trigger: 'change' }
          ],
          status: [
            {required: true, message: '请选择版本状态', trigger: 'change' }
          ]
        }
      }
    },
    methods: {
      handleSizeChange(val) {
       this.paginationData.pageSize = val;
       this.getPages();       
      },
      handleCurrentChange(val) {
        this.paginationData.currentPage = val;
        this.getPages();
      },
      getPages(){
        //axios请求方式，通过this.request使用分装好的axios实例
        this.request.get("/manageApp/getPage",{
          params:{
            app_key: this.app_key,
            version_name: this.version_name,
            status:this.status,
            cuurentPage: this.paginationData.currentPage,
            pageSize: this.paginationData.pageSize
          }
        }).then(res => {
            if(res.code == 200){
                this.tableData = res.data.records;
                this.paginationData.total = res.data.total;
                this.paginationData.currentPage = res.data.current;
                this.paginationData.pageSize = res.data.size;
            }else{
                this.$message({
                  message: res.msg,
                  type: 'error'
                });
            }
        })
      },
      editOpen(row) {
        this.row = {
            update_status : row.update_status,
            status: row.status,
            version_code: row.version_code,
            version_name: row.version_name,
            modify_content: row.modify_content,  
            app_key: row.app_key,
            id: row.id       
        }
        this.editDialogVisible = true
      },
      editClose(){
        this.$refs['editForm'].resetFields()
        this.row = {}
        this.editDialogVisible = false
        this.file = null;
      },
      editConfirm(){
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            this.$alert('是否确定编辑', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                const formData = new FormData();
                formData.append('file', this.file);
                formData.append('app_key',this.row.app_key);
                formData.append('version_name', this.row.version_name);
                formData.append('version_code', this.row.version_code);
                formData.append('modify_content', this.row.modify_content);
                formData.append('update_status', this.row.update_status);
                formData.append('status', this.row.status);
                formData.append('id',this.row.id);
                if(action == 'confirm'){
                  this.loading = true;
                  this.request.post("/manageApp/update",formData).then(res => {
                      if(res.code == 200){
                          this.$message({
                            message: res.msg,
                            type: 'success'
                          });
                          this.editClose()
                          this.getPages()
                      }else{
                          this.$message({
                            message: res.msg,
                            type: 'error'
                          });
                      }
                      this.loading = false;
                  }).catch(err =>{
                    this.loading = false;
                  })
                }
              }
            });
          }else{
            this.$message({
              message: '请先规范填写表单信息',
              type: 'warning'
            });
          }
        });
      },
      addOpen(){
        this.row = {}
        this.addDialogVisible = true
      },
      addClose(){
        this.$refs['addForm'].resetFields()
        this.row = {}
        this.addDialogVisible = false
        this.file = null;
      },
      addConfirm(){
        if(this.file == null){
            this.$message({
              message: '请先上传apk文件',
              type: 'warning'
            });
            return;
        }
        this.$refs['addForm'].validate((valid) => {
          if (valid) {
            this.$alert('是否确定新增', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                if(action == 'confirm'){
                  const formData = new FormData();
                  formData.append('file', this.file);
                  formData.append('app_key',this.row.app_key);
                  formData.append('version_name', this.row.version_name);
                  formData.append('version_code', this.row.version_code);
                  formData.append('modify_content', this.row.modify_content);
                  formData.append('update_status', this.row.update_status);
                  formData.append('status', this.row.status);
                  this.loading = true;
                  this.request.post("/manageApp/add",formData).then(res => {
                      if(res.code == 200){
                          this.$message({
                            message: res.msg,
                            type: 'success'
                          });
                          this.addClose()
                          this.getPages()
                      }else{
                          this.$message({
                            message: res.msg,
                            type: 'error'
                          });
                      }
                      this.loading = false;
                  }).catch(err =>{
                    this.loading = false;
                  })
                }
              }
            });
          }else{
            this.$message({
              message: '请先规范填写表单信息',
              type: 'warning'
            });
          }
        });
      },
      deleteRow(row) {
        this.$alert('是否确定删除', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            if(action == 'confirm'){
              this.request.post("/manageApp/delete",{
                id: row.id
              }).then(res => {
                  if(res.code == 200){
                      this.$message({
                        message: res.msg,
                        type: 'success'
                      });
                      this.getPages()
                  }else{
                      this.$message({
                        message: res.msg,
                        type: 'error'
                      });
                  }
              })
            }
          }
        });
      },
      deleteBatch(){
        var selectedList = this.$refs.multipleTable.selection
        if(selectedList.length<=0){
          this.$message({
            message: '请选择至少一条数据',
            type: 'warning'
          });
          return
        }
        var ids = []
        for(var i=0;i<selectedList.length;i++){
          ids.push(selectedList[i].id)
        }
        this.$alert('是否确定删除', '提示', {
          confirmButtonText: '确定',
          callback: action => { 
            if(action == 'confirm'){
              this.request.post("/manageApp/deleteBatch",{
                ids: JSON.stringify(ids)
              }).then(res => {
                  if(res.code == 200){
                      this.$message({
                        message: res.msg,
                        type: 'success'
                      });
                      this.getPages()
                  }else{
                      this.$message({
                        message: res.msg,
                        type: 'error'
                      });
                  }
              })
            }
          }
        })
      },
      beforeApkUpload(file){
        const parser = new ApkParser(file);
        const msg = this.$message({
          message: '正在解析apk文件',
          duration: 0
        });
        const that=this;
        parser
          .parse()
          .then((result) => {
            //this.appIcon = result.icon;
            this.row={
              version_code: result.versionCode,
              version_name: result.versionName,
              app_key: result.package,
              update_status : that.row.update_status,
              status: that.row.status,
              modify_content: that.row.modify_content,  
              id: that.row.id    
            }
            this.file = file;
            console.log(file)
            msg.close();
            this.$message.success('解析成功');
            //this.row.version_code = result.versionCode;
            //this.row.version_name = result.versionName;
            //this.row.app_key = result.package;
            //this.appName = result.application.label[0];
            //this.byteSize = file.size / 1024;
            //let size = file.size; //byte
            //size = size / 1024; //kb
            //size = (size / 1024).toFixed(2); //mb
            //this.appSize = size + 'm';
            //this.getFileMD5(file);
          })
          .catch((err) => {
            msg.close();
            this.$message.error('解析失败，请稍后再试');
          });
         return false;
      },
      deleteSubmitFile(){
        this.file = null;
      }
    },
    mounted () {
      window.addEventListener('resize', () => {
	      this.tableHeight = window.innerHeight - 320
      })
    },
    created(){ //创建
        this.getPages();
    },
}
</script>

<style scoped>
#body{
    display: flex;
    flex-direction: column;
    align-items: center;
}
#tableCrad{
    width: 100%;
}
#btnRow{
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}
#pageDevice{
    text-align: right;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
</style>